package dominion.model.actions.base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import dominion.model.Card;
import dominion.model.GameBoard;
import dominion.model.Player;
import dominion.model.actions.Action;
import dominion.utils.Constants;

public class Spy extends Action {

	public Spy() {
		cost = 4;
	}

	@Override
	public Card clone() {
		return new Spy();
	}

	@Override
	public String toString() {
		return "Spy";
	}

	@Override
	public String getDescription() {
		StringBuffer sb = new StringBuffer();
		sb.append(super.getDescription());
		sb.append("Each player (including you) reveals the top card of his deck\n");
		sb.append("and either discards it or puts it back, your choice.\n");
		return sb.toString();
	}

	@Override
	public void doAction(Player player, GameBoard board, List<Player> players) throws IOException {
		player.drawCard();
		playedCard(player);

		Constants.printer.print(player.getName() + ", type either \"keep\" or \"toss\".");
		for (Player current : players)
		{
			if (current.hasCounter() && !(current.equals(player)))
			{
				Constants.printer.print("Player " + current.getName() + " has a Moat and is unaffected.");
				continue;
			}
			Constants.printer.print("For player " + current.getName() + ":");
			Card card = current.revealTopLib();
			Constants.printer.print("|" + card.toString() + "|");

			String choice = null;
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			while (true)
			{
				choice = in.readLine().trim().toLowerCase();
				if (choice.equals("keep"))
				{
					Constants.printer.print(card.toString() + " is replaced.");
					break;
				}
				else if (choice.equals("toss"))
				{
					Constants.printer.print(card.toString() + " is discarded.");
					card = current.drawTopCardFromDeck(Constants.LIBRARY_DECK);
					current.addToDeck(card, Constants.DISCARD_DECK);
					break;
				}
				else
				{
					Constants.printer.print("Invalid choice.");
				}
			}
		}
		Constants.printer.print("New hand:");
		Constants.printer.print(player.printHand());
	}
}
